import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controller/authLoginController.dart';
import '../controller/themeController.dart';

class EditProfilePage extends StatefulWidget {
  const EditProfilePage({super.key});

  @override
  State<EditProfilePage> createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
  final Authlogincontroller authController = Get.find<Authlogincontroller>();
  final ThemeController themeController = Get.find<ThemeController>();
  final _formKey = GlobalKey<FormState>();
  final _nicknameController = TextEditingController();
  final _phoneController = TextEditingController();
  final _bioController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 初始化表单数据
    _nicknameController.text = authController.emailController.text.split('@')[0];
    if(authController.phoneController.text != null){
      _phoneController.text = authController.phoneController.text;
    }else{
      _phoneController.text = '';
    }
    _bioController.text = '';
  }

  @override
  void dispose() {
    _nicknameController.dispose();
    _phoneController.dispose();
    _bioController.dispose();
    super.dispose();
  }

  Future<void> _saveProfile() async {
    if (_formKey.currentState!.validate()) {
      try {
        var data = {
          "bio": _bioController.text,
          "phone": _phoneController.text,
          "nickname": _nicknameController.text,
        };
        var res = await authController.editInfo(data);
        
        if (res['code'] == 200) {
          Get.snackbar(
            '成功',
            '个人信息已更新',
            backgroundColor: themeController.themeColor.withOpacity(0.1),
            colorText: themeController.themeColor,
            duration: const Duration(seconds: 2),
          );
          Get.back();
        } else {
          Get.snackbar(
            '失败',
            res['msg'] ?? '更新失败',
            backgroundColor: Colors.red.withOpacity(0.1),
            colorText: Colors.red,
            duration: const Duration(seconds: 2),
          );
        }
      } catch (e) {
        Get.snackbar(
          '错误',
          '保存失败: $e',
          backgroundColor: Colors.red.withOpacity(0.1),
          colorText: Colors.red,
          duration: const Duration(seconds: 2),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('编辑个人信息'),
        centerTitle: true,
        backgroundColor: themeController.themeColor,
        foregroundColor: Colors.white,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // 头像部分
              Center(
                child: Stack(
                  children: [
                    CircleAvatar(
                      radius: 50,
                      backgroundColor: themeController.themeColor,
                      child: const Icon(
                        Icons.person,
                        size: 50,
                        color: Colors.white,
                      ),
                    ),
                    Positioned(
                      right: 0,
                      bottom: 0,
                      child: Container(
                        padding: const EdgeInsets.all(4),
                        decoration: BoxDecoration(
                          color: themeController.themeColor,
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.camera_alt,
                          color: Colors.white,
                          size: 20,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 32),
              // 昵称输入框
              // TextFormField(
              //   controller: _nicknameController,
              //   decoration: InputDecoration(
              //     labelText: '昵称',
              //     prefixIcon: const Icon(Icons.person_outline),
              //     border: OutlineInputBorder(
              //       borderRadius: BorderRadius.circular(12),
              //     ),
              //   ),
              //   validator: (value) {
              //     if (value == null || value.isEmpty) {
              //       return '请输入昵称';
              //     }
              //     return null;
              //   },
              // ),
              const SizedBox(height: 16),
              // 手机号输入框
              TextFormField(
                controller: _phoneController,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                  labelText: '手机号',
                  prefixIcon: const Icon(Icons.phone_outlined),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                validator: (value) {
                  if (value != null && value.isNotEmpty) {
                    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) {
                      return '请输入有效的手机号';
                    }
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              // 个人简介输入框
              TextFormField(
                controller: _bioController,
                maxLines: 3,
                decoration: InputDecoration(
                  labelText: '个人简介',
                  prefixIcon: const Icon(Icons.description_outlined),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
              const SizedBox(height: 32),
              // 保存按钮
              ElevatedButton(
                onPressed: _saveProfile,
                style: ElevatedButton.styleFrom(
                  backgroundColor: themeController.themeColor,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: const Text(
                  '保存',
                  style: TextStyle(fontSize: 16),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
} 